package com.bodacn.keypoint;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;

import android.util.DisplayMetrics;
import android.util.JsonReader;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.widget.PopupWindow.INPUT_METHOD_NEEDED;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentTransProc extends Fragment implements View.OnClickListener {
    public static String TAG=FragmentTransProc.class.getName();
    public static final int msgFocusBarcode = 1001;
    public static final int MSG_SCANBARCODE = 9001;
    public static final int MSG_DetailOver =9002;
    public static final int MSG_MasterOver = 9003;
    public static final int MSG_ERRMSG =9008;
    public static final int MSG_OrderOver=9009;
    public static final int MSG_TransOver=9010;
    LinearLayout mainLinerLayout;
    ReentrantLock reentrantLock = new ReentrantLock();
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    SQLiteDatabase tmpdb;
    //全局变量
    Toast curToast;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curFactory="",curDepart,CPUID;
    boolean curActive=false;
    EditText edit_OrderNo;
    JSONArray detailJson,masterJson,tmpJson;
    String PrBarcode="";
    Button btn_find,btn_saveData,btn_AddEmpProc;
    ListView masterList,detailList;
    TextView Total_SAM,Total_RealValue;
    EditText edt_WorkNo,edt_WorkName,edt_SAM,edt_RealValue,edt_MaxValue;
    private ProgressDialog waitDialog = null;
    JSONArray orderJSON,headJSON,resultJson;
    LinearLayout templetlisthead;
    ListView selectTempletList;
    String selOrderNo="",selStyleNo="",selStyleSort="";
    //全局变量
    View contentView;
    boolean AllowScan=true;

    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public FragmentTransProc() {
        // Required empty public constructor
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        //全局App;
        try {
            detailJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println(TAG+"onCreate-------------------------------------1");
        //创建适配器
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerTransProc(new MainActivity.OnTransParamsListenerTransProc() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        System.out.println(mParams);
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(this.getClass().getName(),"LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir= mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            curFactory=mParams.get("Factory").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d(this.getClass().getName(),"LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }

                        if ((paramComm=="Barcode")&&curActive){
                            String barcode=mParams.get("Barcode").toString();

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        System.out.println(TAG+"onCreate-------------------------------------2");
        //打开或创建数据库文件;
        OpenCreateDB();
        //删除数据;
        tmpdb.execSQL("Delete from TransProcSon");
    }

    //自动刷新数据
    private void GetProc(String paramOperType) {
        System.out.println(TAG+":准备刷新明细图表");
        if (paramOperType.equals("Master")){
            try {
                detailJson=new JSONArray("[]");
                DetailListAdapter detailListAdapter = new DetailListAdapter(getContext());
                detailList.setAdapter(detailListAdapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        String sqlcmd="Exec KeyPoint_TransPrintGetProc @OperType='"+paramOperType+"',@DepartNo='" + curDepartNo
                +"',@OrderNo='" + selOrderNo+"',@StyleNo='" + selStyleNo
                +"',@StyleSort='" + selStyleSort+"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlcmd);
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_trans_proc, container, false);
        contentView = root;
        InitView(root);
        return root;
    }
    //初始化;showAtLocation
    public void InitView(View view){
        //初始提醒;
        mainLinerLayout=view.findViewById(R.id.mainLinerLayout);
        view.findViewById(R.id.btn_saveData).setOnClickListener(this);
        curToast = Toast.makeText(getContext(), "", Toast.LENGTH_LONG);
        curToast.setGravity(Gravity.CENTER, 0, 0);
        waitDialog= new ProgressDialog(getContext());
        waitDialog.setTitle(getString(R.string.SystemHint));
        edit_OrderNo=view.findViewById(R.id.edit_OrderNo);
        btn_find=view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_AddEmpProc=view.findViewById(R.id.btn_AddEmpProc);
        btn_AddEmpProc.setOnClickListener(this);
        btn_saveData=view.findViewById(R.id.btn_saveData);
        btn_saveData.setOnClickListener(this);
        masterList=view.findViewById(R.id.masterList);
        masterList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GetDetail(position);
            }
        });
        detailList=view.findViewById(R.id.detailList);
        Total_SAM=view.findViewById(R.id.Total_SAM);
        Total_RealValue=view.findViewById(R.id.Total_RealValue);

    }

    private void showPopSonProc(final int paramPostion, String paramTitle, final int paramSerial, final String paramWorkNo,final String paramWorkName,final String paramMaxValue){
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View pull_input=inflater.inflate(R.layout.fragment_trans_proc_popson, null);
        edt_WorkNo=pull_input.findViewById(R.id.edt_WorkNo);
        edt_WorkNo.setEnabled(false);
        edt_WorkNo.setOnClickListener(this);
        edt_WorkName=pull_input.findViewById(R.id.edt_WorkName);
        edt_WorkName.setOnClickListener(this);
        edt_SAM=pull_input.findViewById(R.id.edt_SAM);
        edt_SAM.setOnClickListener(this);
        edt_RealValue=pull_input.findViewById(R.id.edt_RealValue);
        edt_RealValue.setOnClickListener(this);
        edt_MaxValue=pull_input.findViewById(R.id.edt_MaxValue);
        edt_MaxValue.setText(paramMaxValue);
        edt_WorkNo.setText(paramWorkNo);
        edt_WorkName.setText(paramWorkName);
        if (detailJson!=null&&detailJson.length()>paramPostion&&paramPostion!=-1){
            try {
                //if (detailJson.optJSONObject(paramPostion).has("PrWorkNo")==true) keyID=detailJson.optJSONObject(paramPostion).getString("PrWorkNo");
                if (detailJson.optJSONObject(paramPostion).has("SAM") == true)
                    edt_SAM.setText(detailJson.optJSONObject(paramPostion).getString("SAM"));
                if (detailJson.optJSONObject(paramPostion).has("RealValue") == true)
                    edt_RealValue.setText(detailJson.optJSONObject(paramPostion).getString("RealValue"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(pull_input).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (edt_WorkNo.getText().toString().length() == 0 ||
                                edt_WorkName.getText().toString().length() == 0 ||
                                edt_SAM.getText().toString().length() == 0 ||
                                edt_RealValue.getText().toString().length() == 0) {
                            curToast.setText("请将数据输入完整!");
                            curToast.show();
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        } else {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                                try {
                                    if (paramPostion >= 0) {
                                        detailJson.optJSONObject(paramPostion).put("WorkName", edt_WorkName.getText().toString());
                                        detailJson.optJSONObject(paramPostion).put("SAM", edt_SAM.getText().toString());
                                        detailJson.optJSONObject(paramPostion).put("RealValue", edt_RealValue.getText().toString());
                                        //更新到数据库
                                        ((BaseAdapter) detailList.getAdapter()).notifyDataSetChanged();
                                        tmpdb.execSQL("Update TransProcSon Set WorkName=?,SAM=?,RealValue=? where WorkNo=?",
                                                new Object[]{edt_WorkName.getText().toString(), edt_SAM.getText().toString(),
                                                        edt_RealValue.getText().toString(), edt_WorkNo.getText().toString()});
                                    } else{
                                        JSONObject jsonObject=new JSONObject();
                                        jsonObject.put("SonSerial",paramSerial);
                                        jsonObject.put("PrWorkNo",paramWorkNo.split("-")[0]);
                                        jsonObject.put("WorkNo",paramWorkNo);
                                        jsonObject.put("WorkName",edt_WorkName.getText().toString());
                                        jsonObject.put("SAM",edt_SAM.getText().toString());
                                        jsonObject.put("RealValue",edt_RealValue.getText().toString());
                                        detailJson.put(jsonObject);
                                        tmpdb.execSQL("insert into TransProcSon(PrWorkNo,SonSerial,WorkNo,WorkName,SAM,RealValue) values(?,?,?,?,?,?)",
                                                new Object[]{paramWorkNo.split("-")[0],paramSerial,paramWorkNo,
                                                        edt_WorkName.getText().toString(),edt_SAM.getText().toString(),
                                                        edt_RealValue.getText().toString()});
                                        ((BaseAdapter) detailList.getAdapter()).notifyDataSetChanged();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            } catch (IllegalAccessException | NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                        }
                        //保存;
                        hideIM(pull_input);
                    }
                }
        ).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                hideIM(pull_input);
                Field field = null;
                try {
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(paramTitle);
        builder.show();
    }

    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }

    @Override
    public void onResume() {
        super.onResume();
        hideBottomUIMenu();
    }





    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        Bundle paramBundle = new Bundle();
        switch (v.getId()){
            case R.id.btn_find:
                if (edit_OrderNo.getText()!=null&&edit_OrderNo.getText().toString().length()>0)
                    showSelectOrder(edit_OrderNo.getText().toString());
                else {
                    curToast.setText("请先输入合约号!");
                    curToast.show();
                }
                break;

            case R.id.edt_WorkName:
            case R.id.edt_WorkNo:
            case R.id.edt_SAM:
            case R.id.edt_RealValue:
                openKeyboard();
                break;
            case R.id.btn_AddEmpProc:
                if (masterList.getCheckedItemPosition()>-1) {
                    try {
                        String workNo = masterJson.optJSONObject(masterList.getCheckedItemPosition()).getString("WorkNo");
                        String workName= masterJson.optJSONObject(masterList.getCheckedItemPosition()).getString("WorkName");
                        String SAM= masterJson.optJSONObject(masterList.getCheckedItemPosition()).getString("SAM");
                        float totalValue=0;
                        //根据WorkNo，找SonSerial
                        int MaxSerial=1;
                        Cursor cursor=tmpdb.rawQuery("Select Max(SonSerial) MaxSerial,sum(realValue) RealValue from TransProcSon where PrWorkNo=?",new String[]{workNo});
                        if (cursor.getCount()>0){
                            cursor.moveToFirst();
                            MaxSerial=cursor.getInt(0)+1;
                            totalValue=cursor.getFloat(1);
                        };
                        cursor.close();
                        float maxValue=Float.parseFloat(SAM)-totalValue;
                        showPopSonProc(-1,"新增工序",MaxSerial,workNo+"-"+MaxSerial,workName,String.valueOf(maxValue));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                break;
            case R.id.btn_saveData:
                if (masterJson!=null){
                    Cursor cursor=tmpdb.rawQuery("Select * from TransProcSon",null);
                    if (cursor.getCount()>0){
                        cursor.close();
                        Runnable run = new Runnable() {
                            @Override
                            public void run() {
                                //将数据读到JSONArray;
                                try {
                                    String TransPrintID=java.util.UUID.randomUUID().toString();
                                    PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement(
                                            "Insert into StyleTransPrintSonProc(SonProcID,TransPrintID,PrWorkNo,SonSerial,WorkNo,WorkName,SAM,RealValue,LastUpdateTime) " +
                                                    "values(newid(),?,?,?,?,?,?,?,getdate())");
                                    Cursor cursor=tmpdb.rawQuery("Select * from TransProcSon",null);
                                    //增加明细表
                                    while (cursor.moveToNext()){
                                        pstmt.setString(1, TransPrintID);
                                        pstmt.setString(2, cursor.getString(cursor.getColumnIndex("PrWorkNo")));
                                        pstmt.setString(3, cursor.getString(cursor.getColumnIndex("SonSerial")));
                                        pstmt.setString(4, cursor.getString(cursor.getColumnIndex("WorkNo")));
                                        pstmt.setString(5, cursor.getString(cursor.getColumnIndex("WorkName")));
                                        pstmt.setString(6, cursor.getString(cursor.getColumnIndex("SAM")));
                                        pstmt.setString(7, cursor.getString(cursor.getColumnIndex("RealValue")));
                                        pstmt.executeUpdate();
                                    }
                                    cursor.close();
                                    pstmt.close();
                                    //调用存储过程;
                                    String SqlComm = " Exec KeyPoint_TransPrintSonProcSave @OperType='SaveTrans',@TransPrintID='" + TransPrintID + "',@OrderNo='" +selOrderNo
                                            + "',@StyleNo='" + selStyleNo + "',@StyleSort='" + selStyleSort
                                            + "',@DepartNo='" + curDepartNo+ "',@DepartName='" + curDepart
                                            + "',@UserNo='" + curLoginUserNo+ "',@UserName='" + curLoginUser
                                            +"',@CPUID='" + CPUID + "',@TermNo='"+ MainApplication.TermNo +"'";
                                    ReadSQLData(SqlComm);
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                    //关闭ProgressDialog
                                    Message msg = new Message();
                                    msg.what = MSG_ERRMSG;
                                    Bundle bundle=new Bundle();
                                    bundle.putString("MSG",e.getMessage());
                                    msg.setData(bundle);
                                    fragmentHandler.removeMessages(msg.what);
                                    fragmentHandler.sendMessage(msg);
                                }
                            }
                        };
                        new Thread(run).start();
                    } else{
                        curToast.setText("没有工序数据,不能保存!");
                        curToast.show();
                    }
                    cursor.close();
                }
                break;

            default:
                break;
        }
    }


    /**
     * 打开软键盘
     */
    private void openKeyboard() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 1000);
    }

    //字符串加减天数
    private String StringToDate(String time,int AddDays) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date= null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        System.out.println(date);
        c.setTime(date);
        c.add(Calendar.DAY_OF_MONTH, AddDays);// 今天+1天
        Date tmpDate = c.getTime();
        System.out.println(tmpDate);
        String s = format.format(tmpDate);
        return s;
    }

    //dp 转换成px
    public int dp2px(float dp)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("requestCode:"+requestCode+" resultCode:"+resultCode);
        //选合约返回
        if ((requestCode==1000)&&(resultCode==1001)){

        }
        hideBottomUIMenu();
    }



    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //从字符串转颜色
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor=Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()>=7)){
            PenColor=Color.parseColor(StrPenColor);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                if (waitDialog.isShowing()==true) waitDialog.cancel();
                String tmpValue;
                //任意消息来均置焦点
                int msgId = msg.what;
                System.out.println("收到的消息是："+msg.what);
                try {
                    switch (msgId) {
                        case MSG_TransOver:
                            fillFormtext();
                            break;
                        case MSG_ERRMSG:
                            Bundle bundle1=msg.getData();
                            String mesg=bundle1.getString("MSG","");
                            curToast.setText(mesg);
                            curToast.show();
                            return;
                        case MSG_OrderOver:
                            //显示表明细
                            if (orderJSON!=null) {
                                SelectTempletListAdapter selectTempletListAdapter = new SelectTempletListAdapter(getContext());
                                selectTempletList.setAdapter(selectTempletListAdapter);
                            }
                            break;
                        case MSG_MasterOver:
                            tmpdb.execSQL("Delete from TransProcSon");
                            //显示明细数据
                            if (masterJson!=null) {
                                MasterListAdapter masterListAdapter = new MasterListAdapter(getContext());
                                masterList.setAdapter(masterListAdapter);
                            }
                            GetProc("Detail");
                            break;
                        case MSG_DetailOver:
                            String PrWorkNo="",WorkNo="",WorkName="",SAM="",RealValue="";
                            int SonSerial=1;
                            for (int i=0;i<tmpJson.length();i++){
                                if (tmpJson.optJSONObject(i).has("SonSerial"))
                                    SonSerial=tmpJson.optJSONObject(i).getInt("SonSerial");
                                if (tmpJson.optJSONObject(i).has("PrWorkNo"))
                                    PrWorkNo=tmpJson.optJSONObject(i).getString("PrWorkNo");
                                if (tmpJson.optJSONObject(i).has("WorkNo"))
                                    WorkNo=tmpJson.optJSONObject(i).getString("WorkNo");
                                if (tmpJson.optJSONObject(i).has("WorkName"))
                                    WorkName=tmpJson.optJSONObject(i).getString("WorkName");
                                if (tmpJson.optJSONObject(i).has("SAM"))
                                    SAM=tmpJson.optJSONObject(i).getString("SAM");
                                if (tmpJson.optJSONObject(i).has("RealValue"))
                                    RealValue=tmpJson.optJSONObject(i).getString("RealValue");
                                tmpdb.execSQL("insert into TransProcSon(PrWorkNo,SonSerial,WorkNo,WorkName,SAM,RealValue) values(?,?,?,?,?,?)",
                                        new Object[]{PrWorkNo,SonSerial,WorkNo,WorkName,SAM,RealValue});
                                System.out.println("SonSerial:"+SonSerial);
                            }
                            GetDetail(0);
                            break;
                        default:
                            break;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    };

    private void GetDetail(int paramPostion){
        try {
            String tmpWorkNo="";
            System.out.println("GetDetail:"+paramPostion);
            detailJson = new JSONArray("[]");
            if (masterJson != null && masterJson.length() > paramPostion) {
                if (masterJson.optJSONObject(paramPostion).has("WorkNo"))
                    tmpWorkNo = masterJson.optJSONObject(paramPostion).getString("WorkNo");
                System.out.println("tmpWorkNo:"+tmpWorkNo);
                Cursor cursor = tmpdb.rawQuery("Select * from TransProcSon where PrWorkNo=?", new String[]{tmpWorkNo});
                while (cursor.moveToNext()) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("SonSerial", cursor.getInt(cursor.getColumnIndex("SonSerial")));
                    jsonObject.put("PrWorkNo", cursor.getString(cursor.getColumnIndex("PrWorkNo")));
                    jsonObject.put("WorkNo", cursor.getString(cursor.getColumnIndex("WorkNo")));
                    jsonObject.put("WorkName", cursor.getString(cursor.getColumnIndex("WorkName")));
                    jsonObject.put("SAM", cursor.getDouble(cursor.getColumnIndex("SAM")));
                    jsonObject.put("RealValue", cursor.getDouble(cursor.getColumnIndex("RealValue")));
                    detailJson.put(jsonObject);
                }
                cursor.close();
                //显示明细数据
                if (detailJson != null) {
                    DetailListAdapter detailListAdapter = new DetailListAdapter(getContext());
                    detailList.setAdapter(detailListAdapter);
                }
            }
            System.out.println(detailJson);
        } catch (JSONException e){
            e.printStackTrace();
        }
    }


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                try{
                    reentrantLock.lock();
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        System.out.println(jsonArray);
                        String OPERTYPE="";
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true) OPERTYPE=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (jsonArray.optJSONObject(0).has("OperType")==true) OPERTYPE=jsonArray.optJSONObject(0).getString("OperType");
                        if (OPERTYPE.toUpperCase().equals("Master".toUpperCase())) {
                            masterJson=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_MasterOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("OrderList".toUpperCase())) {
                            orderJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_OrderOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("Detail".toUpperCase())) {
                            tmpJson=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_DetailOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("SaveTrans".toUpperCase())) {
                            resultJson=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_TransOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }

                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                    }else{
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle=new Bundle();
                        bundle.putString("MSG","未返回任何数据!");
                        msg.setData(bundle);
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //显示预排单;
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    Bundle bundle=new Bundle();
                    bundle.putString("MSG",e.getMessage());
                    msg.setData(bundle);
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                    reentrantLock.unlock();
                }finally {
                    reentrantLock.unlock();
                }
                //允许扫描
                AllowScan=true;
            }

        };
        new Thread(run).start();
    }


    //填充界面显示内容;
    private void fillFormtext(){
        if (resultJson.length()>0)
        {
            try {
                AlertDialog alertDialog;
                 if (resultJson.getJSONObject(0).has("ResultInfo")==true) {
                    alertDialog = new AlertDialog.Builder(getContext())
                            .setTitle("系统提示").setMessage(resultJson.getJSONObject(0).getString("ResultInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideBottomUIMenu();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
                if (resultJson.getJSONObject(0).has("ErrInfo")==true)
                {
                    alertDialog = new AlertDialog.Builder(getContext())
                            .setTitle("系统提示").setMessage(resultJson.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideBottomUIMenu();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


    }
    //打开数据库
    public void OpenCreateDB(){
        if (tmpdb==null) {
            MainActivity activity = (MainActivity) getActivity();
            tmpdb = activity.mainDB;
        }
    }


    //自定义适配器;
    public final class MasterListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public MasterListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return masterJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return masterJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.fragment_trans_proc_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            int color = getResources().getColor(R.color.text_black);
            int backcolor = getResources().getColor(R.color.content);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (masterJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = masterJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if (masterJson.optJSONObject(position).has("WorkNo") == true) {
                    ((TextView)view.findViewById(R.id.Item_WorkNo)).setText(masterJson.optJSONObject(position).getString("WorkNo"));
                    ((TextView)view.findViewById(R.id.Item_WorkNo)).setTextColor(color);
                }
                if (masterJson.optJSONObject(position).has("WorkName") == true) {
                    ((TextView)view.findViewById(R.id.Item_WorkName)).setText(masterJson.optJSONObject(position).getString("WorkName"));
                    ((TextView)view.findViewById(R.id.Item_WorkName)).setTextColor(color);
                }
                if (masterJson.optJSONObject(position).has("SAM") == true) {
                    ((TextView)view.findViewById(R.id.Item_SAM)).setText(masterJson.optJSONObject(position).getString("SAM"));
                    ((TextView)view.findViewById(R.id.Item_SAM)).setTextColor(color);
                }
                if (masterJson.optJSONObject(position).has("RealValue") == true) {
                    ((TextView)view.findViewById(R.id.Item_RealValue)).setText(masterJson.optJSONObject(position).getString("RealValue"));
                    ((TextView)view.findViewById(R.id.Item_RealValue)).setTextColor(color);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","MasterListAdapter_position:"+position);
            return view;
        }
    }


    //自定义适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.fragment_trans_proc_splititem, null, false);
            int pullVatListWidth=parent.getWidth();
            int color = getResources().getColor(R.color.text_black);
            int backcolor = getResources().getColor(R.color.content);
            ViewHolder holder = new ViewHolder();
            holder.btn_delItem = view.findViewById(R.id.btn_delItem);
            holder.btn_delItem.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    try {
                        String workNo=detailJson.getJSONObject(position).getString("WorkNo");
                        detailJson.remove(position);
                        ((BaseAdapter)detailList.getAdapter()).notifyDataSetChanged();
                        tmpdb.execSQL("Delete from TransProcSon where WorkNo=?",new Object[]{workNo});
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            holder.btn_editItem = view.findViewById(R.id.btn_editItem);
            holder.btn_editItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        String prWorkNo = detailJson.optJSONObject(position).getString("PrWorkNo");
                        String workNo = detailJson.optJSONObject(position).getString("WorkNo");
                        String SAM= detailJson.optJSONObject(position).getString("SAM");
                        float totalValue=0;
                        //根据WorkNo，找SonSerial
                        int MaxSerial=1;
                        Cursor cursor=tmpdb.rawQuery("Select Max(SonSerial) MaxSerial,sum(1.00*realValue) RealValue from TransProcSon where PrWorkNo=? and WorkNo<>?",new String[]{prWorkNo,workNo});
                        if (cursor.getCount()>0){
                            cursor.moveToFirst();
                            totalValue=cursor.getFloat(1);
                        };
                        cursor.close();
                        float maxValue=Float.parseFloat(SAM)-totalValue;
                        showPopSonProc(position,"修改工序",
                                detailJson.optJSONObject(position).getInt("SonSerial"),
                                detailJson.optJSONObject(position).getString("WorkNo"),
                                detailJson.optJSONObject(position).getString("WorkName"),String.valueOf(maxValue));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            view.setTag(holder);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (detailJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = detailJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if (detailJson.optJSONObject(position).has("WorkNo") == true) {
                    ((TextView)view.findViewById(R.id.Item_WorkNo)).setText(detailJson.optJSONObject(position).getString("WorkNo"));
                    ((TextView)view.findViewById(R.id.Item_WorkNo)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("WorkName") == true) {
                    ((TextView)view.findViewById(R.id.Item_WorkName)).setText(detailJson.optJSONObject(position).getString("WorkName"));
                    ((TextView)view.findViewById(R.id.Item_WorkName)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("SAM") == true) {
                    ((TextView)view.findViewById(R.id.Item_SAM)).setText(detailJson.optJSONObject(position).getString("SAM"));
                    ((TextView)view.findViewById(R.id.Item_SAM)).setTextColor(color);
                }
                if (detailJson.optJSONObject(position).has("RealValue") == true) {
                    ((TextView)view.findViewById(R.id.Item_RealValue)).setText(detailJson.optJSONObject(position).getString("RealValue"));
                    ((TextView)view.findViewById(R.id.Item_RealValue)).setTextColor(color);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailListAdapter_position:"+position);
            return view;
        }

        //提取出来方便点
        public final class ViewHolder {
            public Button btn_delItem;
            public Button btn_editItem;
        }
    }

    //显示工序选择
    private void showSelectOrder(String paramOrderNo){
        try {
            headJSON=new JSONArray("[{\"TitleName\":\"OrderNo\",\"TitleText\":\"合约号\",\"TxtSize\":18,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}," +
                    "{\"TitleName\":\"StyleNo\",\"TitleText\":\"货号\",\"TxtSize\":18,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"StyleSort\",\"TitleText\":\"款式\",\"TxtSize\":18,\"TxtWidth\":100,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建布局
        String dgCaption="制单选择";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectTemplet=inflater.inflate(R.layout.select_templet, null);
        templetlisthead=selectTemplet.findViewById(R.id.templetlisthead);
        //创建表头;
        CreateListHead();
        //Activity.findViewById最终还是会调用View.findViewById
        selectTempletList=selectTemplet.findViewById(R.id.selectTempletList);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(selectTemplet).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {

                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width = 800;
        params.height = 600 ;
        alterDialog.getWindow().setAttributes(params);
        selectTempletList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    view.setSelected(true);
                    if (orderJSON.optJSONObject(position).has("OrderNo")==true)
                        selOrderNo=orderJSON.optJSONObject(position).getString("OrderNo");
                    if (orderJSON.optJSONObject(position).has("StyleNo")==true)
                        selStyleNo=orderJSON.optJSONObject(position).getString("StyleNo");
                    if (orderJSON.optJSONObject(position).has("StyleSort")==true)
                        selStyleSort=orderJSON.optJSONObject(position).getString("StyleSort");
                    edit_OrderNo.setText(selOrderNo);
                    GetProc("Master");
                    alterDialog.dismiss();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        searchOrderNoData(paramOrderNo);
    }

    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(getContext());
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }

    //刷新缸布列表;
    private void searchOrderNoData(String SearchParam)
    {
        String SqlComm="Exec KeyPoint_TransPrintGetOrderNo @OrderNO='" + SearchParam + "',@OPERTYPE='OrderList',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return orderJSON.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<orderJSON.length())
                    return orderJSON.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.select_templet_item, null, false);
            //变换背景色
            /*
            if (position%2==1) {
                view.setBackgroundColor(getResources().getColor(R.color.content));
            }
            */
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,60));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<orderJSON.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (orderJSON.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = orderJSON.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (orderJSON.optJSONObject(curPosition).has(TitleName)==true) tmpValue= orderJSON.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        curActive=true;

    }

    @Override
    public void onPause() {
        super.onPause();
        curActive=false;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        curActive=!hidden;
        //读配置文件
        System.out.println("curActive:"+curActive);
    }
}
